#include "daemon_sub_process_monitor.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/reboot.h>
#include "log.h"
/**
 * @brief 子进程监控器的初始化
 */
sub_process_monitor_t* daemon_sub_process_monitor_init(char *sub_process_arg) 
{
    sub_process_monitor_t *monitor = malloc(sizeof(sub_process_monitor_t));
    monitor->sub_process_arg = sub_process_arg;
    monitor->failed_count = 0;
    monitor->sub_process_pid = -1;

    return monitor;
}


/**
 * @brief 子进程监控器 检查和启动
 */
int daemon_sub_process_monitor_checkAndStart(sub_process_monitor_t *monitor)
{
    int over_status=0;
    // 要启动的原则 ： 1 子进程根本没有被启动过 sub_process_pid = -1  、  2 启动过 waitpid(sub_process_pid, &status, WNOHANG)之后挂了 返回值不为0
    if(monitor->sub_process_pid == -1 || waitpid(monitor->sub_process_pid, &over_status, WNOHANG)!=0)
    {
        //如果是意外结束 要记失败次数
        if(over_status!=0)
        {
            monitor->failed_count++;
            if( monitor->failed_count>=FAILED_MAX_COUNT)
            {
                reboot(RB_AUTOBOOT);
            }
        }

        //需要启动
        //1 fork  2 execve 

        monitor->sub_process_pid =  fork();
        if( monitor->sub_process_pid==0)
        {
            //子进程
            char *args[] = {PROCESS_CMD, monitor->sub_process_arg, NULL};// gateway app . gateway ota
            execve(PROCESS_CMD, args, NULL);
            //execve失败
            log_error("子程序%s启动失败", monitor->sub_process_arg);
            exit(EXIT_FAILURE);

        }


    }


    return 0;
}


/**
 * @brief 子进程监控器的销毁
 */
void daemon_sub_process_monitor_destroy(sub_process_monitor_t *monitor);